package com.greenant.store.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import com.avos.avoscloud.AVAnalytics;
import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVFile;
import com.avos.avoscloud.AVInstallation;
import com.avos.avoscloud.AVOSCloud;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVQuery;
import com.avos.avoscloud.AVQuery.CachePolicy;
import com.avos.avoscloud.AVRelation;
import com.avos.avoscloud.AVUser;
import com.avos.avoscloud.DeleteCallback;
import com.avos.avoscloud.RequestPasswordResetCallback;
import com.avos.avoscloud.SaveCallback;
import com.avos.avoscloud.SignUpCallback;
import com.greenant.store.AntHomeApplication;
import com.greenant.store.R;
import com.greenant.store.bean.AntGoods;
import com.greenant.store.bean.AntGoodsBase;
import com.greenant.store.bean.AntGoodsStyles;
import com.greenant.store.bean.AntGoodsStylesBase;
import com.greenant.store.bean.EMCompany;
import com.greenant.store.bean.EMOrder;
import com.greenant.store.bean.EMRecv;
import com.greenant.store.bean.EMRecvList;
import com.greenant.store.bean.Evaluate;
import com.greenant.store.bean.GoodsBaseList;
import com.greenant.store.bean.GoodsKind;
import com.greenant.store.bean.GoodsKindBase;
import com.greenant.store.bean.GoodsList;
import com.greenant.store.bean.GoodsRecommend;
import com.greenant.store.bean.IncomeInfo;
import com.greenant.store.bean.Order;
import com.greenant.store.bean.OrderList;
import com.greenant.store.bean.OrderStatusCode;
import com.greenant.store.bean.ServerSection;
import com.greenant.store.bean.ServiePhone;
import com.greenant.store.bean.ShippingAddr;
import com.greenant.store.bean.ShoppingCart;
import com.greenant.store.bean.StoreInfo;
import com.greenant.store.bean.UserIdentification;
import com.greenant.store.bean.VersionInfo;
import com.greenant.store.bean.WebDeposit;
import com.greenant.store.bean.WithdrawRecord;
import com.greenant.store.fragment.EarningListFragment;
import com.greenant.store.fragment.OrdersListFragment;
import com.greenant.store.utils.iLog;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.util.Log;

public class RetrieveDataAsyn
{
    private static RetrieveDataAsyn sInstance;
    private final String TAG = "RetrieveDataAsyn";

    private ExecutorService mExecutorService = Executors.newCachedThreadPool();
    private Handler mHandler = new Handler(Looper.getMainLooper());

    private boolean isInit = false;

    private RetrieveDataAsyn()
    {

    }

    public static RetrieveDataAsyn getInstance()
    {
        if (sInstance == null)
        {
            synchronized ("")
            {
                if (sInstance == null)
                {
                    sInstance = new RetrieveDataAsyn();
                }
            }
        }
        return sInstance;
    }

    public void avInit(Context ctx)
    {
        AVOSCloud.initialize(ctx,
            "ak17uowdqweoh18wn56qe5crtikhr3wzjv8751xo37m2f8o6",
            "x8xa025tojekkbx69fmt7m6h1jh4zrhhfu5psepi82890g8e");
        
        AVAnalytics.enableCrashReport(ctx, true);
        AVOSCloud.setLastModifyEnabled(true);
        AVOSCloud.setDebugLogEnabled(true);

    }

    public void registerAVClass(Context ctx)
    {
        // AVOSCloud.setDebugLogEnabled(true);
        // AVAnalytics.enableCrashReport(ctx, true);
        AVObject.registerSubclass(AntGoods.class);
        AVObject.registerSubclass(AntGoodsBase.class);
        AVObject.registerSubclass(GoodsKind.class);
        AVObject.registerSubclass(GoodsKindBase.class);
        AVObject.registerSubclass(AntGoodsStyles.class);
        AVObject.registerSubclass(AntGoodsStylesBase.class);
        AVObject.registerSubclass(GoodsRecommend.class);
        AVObject.registerSubclass(ServerSection.class);
        AVObject.registerSubclass(ShoppingCart.class);
        AVObject.registerSubclass(ShippingAddr.class);
        AVObject.registerSubclass(StoreInfo.class);
        AVObject.registerSubclass(Order.class);
        AVObject.registerSubclass(ServiePhone.class);
        AVObject.registerSubclass(VersionInfo.class);
        AVObject.registerSubclass(Evaluate.class);
        AVObject.registerSubclass(AntGoodsBase.class);
        AVObject.registerSubclass(IncomeInfo.class);
        AVObject.registerSubclass(WebDeposit.class);
        AVObject.registerSubclass(WithdrawRecord.class);
        AVObject.registerSubclass(UserIdentification.class);
        AVObject.registerSubclass(EMRecv.class);
        AVObject.registerSubclass(EMOrder.class);
        AVObject.registerSubclass(EMCompany.class);

        // 消息通知注册
        AVInstallation.getCurrentInstallation().saveInBackground(new SaveCallback()
        {

            @Override
            public void done(AVException arg0)
            {
                AntHomeApplication.installationId = AVInstallation
                    .getCurrentInstallation().getInstallationId();
            }
        });

        isInit = true;
        Log.d(TAG, "installationId:" + AntHomeApplication.installationId);
    }

    private void checkIsInit()
    {
        if (!isInit)
        {
            avInit(AntHomeApplication.context);
            registerAVClass(AntHomeApplication.context);
        }
    }

    public void getServiePhone(final int requestId,
        final RetrieveDataListener listener)
    {
        Log.d("CEXX", "CEXX ---> getServiePhone");
        mExecutorService.submit(new Runnable()
        {
            @Override
            public void run()
            {
                checkIsInit();
                ServiePhone serviePhone = null;

                AVQuery<ServiePhone> query = AVQuery
                    .getQuery(ServiePhone.class);
                try
                {
                    serviePhone = query.getFirst();
                } catch (AVException e)
                {
                    e.printStackTrace();
                    Log.d("CEXX",
                        "CEXX ---> getServiePhone ---> e : " + e.toString());
                }

                final ServiePhone result = serviePhone;
                mHandler.post(new Runnable()
                {
                    @Override
                    public void run()
                    {
                        listener.dataRetrieved(requestId, result);
                    }
                });
            }
        });
    }

    public void getGoodsDetail(final String objectId, final int requestId,
        final RetrieveDataListener listener)
    {
        mExecutorService.submit(new Runnable()
        {
            @Override
            public void run()
            {
                checkIsInit();
                AVQuery<AntGoods> query = AVQuery.getQuery(AntGoods.class);
                query.include(AntGoods.ATTR_UPTOWNS);
                AntGoods temp = null;
                query.setCachePolicy(CachePolicy.NETWORK_ELSE_CACHE);
                try
                {
                    temp = query.get(objectId);
                    Log.d(TAG, "Query getGoodsDetail success." + temp
                        + " objectId:" + objectId);
                } catch (AVException exception)
                {
                    Log.e(TAG, "Query getGoodsDetail failed.", exception);
                }
                final AntGoods result = temp;
                mHandler.post(new Runnable()
                {
                    @Override
                    public void run()
                    {
                        listener.dataRetrieved(requestId, result);
                    }
                });
            }
        });
    }

    /**
     * 根据订单类型，获取对应订单
     * @param userId
     * @param orderTypes
     * @param requestId
     * @param listener
     * @since 3.8
     */
    public void getMyOrderByType(final String userId, final int orderType,
        final int start, final int expectedCount, final int requestId,
        final RetrieveDataListener listener)
    {
        mExecutorService.submit(new Runnable()
        {
            @Override
            public void run()
            {
                checkIsInit();
                try
 {
					final AVQuery<Order> query = AVQuery.getQuery(Order.class);
					// query.whereEqualTo(Order.ATTR_CUSTOMID, userId);
					iLog.d(TAG, "ATTR_CUSTOMID:" + userId);
					// TODO 替换为商店的ID
					query.whereEqualTo(Order.ATTR_STOREID, userId);

					// 订单类型
					ArrayList<Integer> orderTypes = new ArrayList<Integer>();
					if (orderType != OrdersListFragment.ORDER_TYPE_ALL) {

						if (orderType == OrdersListFragment.ORDER_TYPE_UNSEND) {
							orderTypes.add(OrderStatusCode.ORDER_PENDING.value());
							orderTypes.add(OrderStatusCode.ORDER_WEIGHED.value());
							query.whereEqualTo(Order.ATTR_HASPAY, 1);
						} else if (orderType == OrdersListFragment.ORDER_TYPE_UNPAY) {
							orderTypes.add(OrderStatusCode.ORDER_WEIGHED.value());
							orderTypes.add(OrderStatusCode.ORDER_WAIT_FOR_PAY.value());
							orderTypes.add(OrderStatusCode.ORDER_PENDING.value());
							orderTypes.add(OrderStatusCode.ORDER_UN_WEIGHED.value());
							query.whereEqualTo(Order.ATTR_HASPAY, 0);
							query.whereContainedIn(Order.ATTR_STATUSCODE, orderTypes);
							
						} else if (orderType == OrdersListFragment.ORDER_TYPE_UNRECEIVE) {
							orderTypes.add(OrderStatusCode.ORDER_WAIT_FOR_SIGN.value());
							orderTypes.add(OrderStatusCode.ORDER_SHIPPED.value());
							orderTypes.add(OrderStatusCode.ORDER_2_STATION.value());
						} else if (orderType == OrdersListFragment.ORDER_TYPE_REFUNDING) {
							orderTypes.add(OrderStatusCode.ORDER_REFUNDING.value());
							orderTypes.add(OrderStatusCode.ORDER_REFUNDED.value());
						} else if (orderType == OrdersListFragment.ORDER_TYPE_FINISHED) {
							orderTypes.add(OrderStatusCode.ORDER_FINISHED.value());
							orderTypes.add(OrderStatusCode.ORDER_SIGNED.value());
						} else if (orderType == OrdersListFragment.ORDER_TYPE_CLOSED) {
							orderTypes.add(OrderStatusCode.ORDER_CLOSED.value());
							orderTypes.add(OrderStatusCode.ORDER_CANCELED.value());
						}

						else {
							orderTypes.add(orderType);
						}

					}
					if (orderTypes != null && orderTypes.size() > 0) {
						query.whereContainedIn(Order.ATTR_STATUSCODE, orderTypes);
					}
					query.setSkip(start);
					query.limit(expectedCount);
					query.setCachePolicy(CachePolicy.NETWORK_ELSE_CACHE);

					query.orderByDescending(Order.ATTR_CREATED_AT);
					// query.orderByAscending(Order.ATTR_STATUSCODE);

					final OrderList orderList = new OrderList();
					orderList.setOrderList(query.find());
					orderList.setTotalNum(query.count());

					mHandler.post(new Runnable() {
						@Override
						public void run() {
							listener.dataRetrieved(requestId, orderList);
						}
					});
				} catch (Exception e)
                {
                    iLog.e(TAG, "getMyOrderByType", e);
                    e.printStackTrace();
                    mHandler.post(new Runnable()
                    {
                        @Override
                        public void run()
                        {
                            listener.dataRetrieved(requestId, null);
                        }
                    });
                }

            }
        });
    }

    /**
     * 关闭订单
     * @param userId
     * @param shoppingCart
     * @param shippingAddr
     * @param customerComment
     * @param deliveryTime
     * @param expectedCount
     * @param requestId
     * @param listener
     */
    public void closeOrder(final String userId, final String orderId,
        final int requestId, final RetrieveDataListener listener)
    {
        mExecutorService.submit(new Runnable()
        {
            @Override
            public void run()
            {
                checkIsInit();
                try
                {
                    final AVQuery<Order> query = AVQuery.getQuery(Order.class);
                    query.whereEqualTo(Order.ATTR_CUSTOMID, userId);
                    query.whereEqualTo(Order.ATTR_ORDERID, orderId);
                    Order order = query.getFirst();
                    order.setStatusCode(OrderStatusCode.ORDER_CLOSED.value());
                    order.save();
                    mHandler.post(new Runnable()
                    {
                        @Override
                        public void run()
                        {
                            listener.dataRetrieved(requestId, new Object());
                        }
                    });
                } catch (Exception e)
                {
                    e.printStackTrace();
                    mHandler.post(new Runnable()
                    {
                        @Override
                        public void run()
                        {
                            listener.dataRetrieved(requestId, null);
                        }
                    });
                }

            }
        });
    }

    /**
     * 修改订单状态
     * @param userId
     * @param shoppingCart
     * @param shippingAddr
     * @param customerComment
     * @param deliveryTime
     * @param expectedCount
     * @param requestId
     * @param listener
     */
	public void updateOrderStatus(final Order order, final int status, final int requestId,
			final RetrieveDataListener listener) {
		mExecutorService.submit(new Runnable() {
			@Override
			public void run() {
				checkIsInit();
				try {
					order.setStatusCode(status);
					order.save();
					mHandler.post(new Runnable() {
						@Override
						public void run() {
							listener.dataRetrieved(requestId, new Object());
						}
					});
				} catch (Exception e) {
					e.printStackTrace();
					mHandler.post(new Runnable() {
						@Override
						public void run() {
							listener.dataRetrieved(requestId, null);
						}
					});
				}

			}
		});
	}

    /**
     * 查询订单详情
     * @param objectId
     * @param requestId
     * @param listener
     */
    public void getOrderDetail(final String objectId, final int requestId,
        final RetrieveDataListener listener)
    {
        mExecutorService.submit(new Runnable()
        {
            @Override
            public void run()
            {
                checkIsInit();
                AVQuery<Order> query = AVQuery.getQuery(Order.class);
                Order temp = null;
                query.setCachePolicy(CachePolicy.NETWORK_ELSE_CACHE);
                try
                {
                    temp = query.get(objectId);
                    Log.d(TAG, "Query getOrderDetail success." + temp
                        + " objectId:" + objectId);
                } catch (AVException exception)
                {
                    Log.e(TAG, "Query getOrderDetail failed.", exception);
                }
                final Order result = temp;
                mHandler.post(new Runnable()
                {
                    @Override
                    public void run()
                    {
                        listener.dataRetrieved(requestId, result);
                    }
                });
            }
        });
    }

    /**
     * 检查更新
     * @since 3.8
     */
    public VersionInfo checkUpdate()
    {
        checkIsInit();
        AVQuery<VersionInfo> query = AVQuery.getQuery(VersionInfo.class);
        VersionInfo temp = null;
        query.setCachePolicy(CachePolicy.NETWORK_ELSE_CACHE);
        query.orderByDescending("updatedAt");
        try
        {
            temp = query.getFirst();
        } catch (AVException e)
        {
            e.printStackTrace();
        }
        return temp;
    }

    /**
     * 评论&反馈
     * @param requestId
     * @param listener
     * @return 返回对象为空的时候，保存不成功；不为空则成功
     */
    public void commentFeedback(final String userId, final String comment,
        final int requestId, final RetrieveDataListener listener)
    {
        mExecutorService.submit(new Runnable()
        {
            @Override
            public void run()
            {
                checkIsInit();
                Evaluate evaluate = new Evaluate();
                evaluate.setUserId(userId);
                evaluate.setComment(comment);
                try
                {
                    evaluate.save();
                    mHandler.post(new Runnable()
                    {
                        @Override
                        public void run()
                        {
                            if (listener != null)
                            {
                                listener.dataRetrieved(requestId, new Object());
                            }

                        }
                    });
                } catch (AVException e)
                {
                    e.printStackTrace();
                    mHandler.post(new Runnable()
                    {
                        @Override
                        public void run()
                        {
                            if (listener != null)
                            {
                                listener.dataRetrieved(requestId, null);
                            }

                        }
                    });
                }

            }
        });
    }

    public void signUp(String username, String password, String email,
        SignUpCallback signUpCallback)
    {
        AVUser user = new AVUser();
        user.setUsername(username);
        user.setPassword(password);
        user.setEmail(email);
        user.signUpInBackground(signUpCallback);
    }

    public void requestPasswordReset(String email,
        RequestPasswordResetCallback callback)
    {
        AVUser.requestPasswordResetInBackground(email, callback);
    }

    /**
     * 检查商品是否在在线库中
     * @param requestId
     * @param listener
     * @return 返回对象为空的时候，保存不成功；不为空则成功
     */
    public void checkIfGoodsOnline(final String goodsCode, final int requestId,
        final RetrieveDataListener listener)
    {
        mExecutorService.submit(new Runnable()
        {
            @Override
            public void run()
            {
                checkIsInit();
                AVQuery<AntGoodsBase> query = AVQuery
                    .getQuery(AntGoodsBase.class);

                query.whereEqualTo(AntGoodsBase.ATTR_GOODCODE, goodsCode);
                try
                {
                    final AntGoodsBase antGoodsBase = query.getFirst();
                    mHandler.post(new Runnable()
                    {
                        @Override
                        public void run()
                        {
                            if (listener != null)
                            {
                                listener.dataRetrieved(requestId, antGoodsBase);
                            }

                        }
                    });
                } catch (AVException e)
                {
                    e.printStackTrace();
                    mHandler.post(new Runnable()
                    {
                        @Override
                        public void run()
                        {
                            if (listener != null)
                            {
                                listener.dataRetrieved(requestId, null);
                            }

                        }
                    });
                }

            }
        });
    }
    
    /**
     * 检查商品是否已经添加到店铺中
     * @param requestId
     * @param listener
     * @return 返回对象为空的时候，保存不成功；不为空则成功
     */
    public void checkIfGoodsAlreadyAdded(final String goodsCode, final String storeId,final int requestId,
        final RetrieveDataListener listener)
    {
        mExecutorService.submit(new Runnable()
        {
            @Override
            public void run()
            {
                checkIsInit();
                AVQuery<AntGoods> query = AVQuery
                    .getQuery(AntGoods.class);

                query.whereEqualTo(AntGoods.ATTR_GOODCODE, goodsCode);
                query.whereEqualTo(AntGoods.ATTR_STOREID, storeId);
                try
                {
                    final AntGoods antGoodsBase = query.getFirst();
                    mHandler.post(new Runnable()
                    {
                        @Override
                        public void run()
                        {
                            if (listener != null)
                            {
                                listener.dataRetrieved(requestId, antGoodsBase);
                            }

                        }
                    });
                } catch (AVException e)
                {
                    e.printStackTrace();
                    mHandler.post(new Runnable()
                    {
                        @Override
                        public void run()
                        {
                            if (listener != null)
                            {
                                listener.dataRetrieved(requestId, null);
                            }

                        }
                    });
                }

            }
        });
    }
    
	public void getStoreInfoByUserId(final int requestId, final RetrieveDataListener listener) {
		final List<StoreInfo> storeInfoList = new ArrayList<StoreInfo>();
		AVUser avUser = AVUser.getCurrentUser();
		if (avUser == null) {
			AntHomeApplication.storeInfos.clear();
			mHandler.post(new Runnable() {
				@Override
				public void run() {
					listener.dataRetrieved(requestId, storeInfoList);
				}
			});
			return;
		}

		final String userId = avUser.getObjectId();
		mExecutorService.submit(new Runnable() {
			@Override
			public void run() {
				checkIsInit();
				AVQuery<StoreInfo> query = AVQuery.getQuery(StoreInfo.class);
				query.setCachePolicy(CachePolicy.NETWORK_ELSE_CACHE);
				query.whereEqualTo(StoreInfo.ATTR_STOREID, userId);
//				query.whereEndsWith(StoreInfo.ATTR_STOREID, "558e0ebbe4b060308e3c8b78");
				try {
					List<StoreInfo> temp = query.find();
					if (temp != null && temp.size() > 0) {
						storeInfoList.addAll(temp);
					}
				} catch (AVException e) {
					e.printStackTrace();
				}

				mHandler.post(new Runnable() {
					@Override
					public void run() {
						AntHomeApplication.storeInfos.clear();
						for(StoreInfo si : storeInfoList) {
							AntHomeApplication.storeInfos.put(si.getStoreid(), si);
						}
						
						if (listener != null) {
							listener.dataRetrieved(requestId, storeInfoList);
						}
					}
				});
			}
		});
	}
    
    public void getGoodsKindByUserId(final int requestId, final RetrieveDataListener listener)
    {
    	final List<GoodsKind> goodsKindList = new ArrayList<GoodsKind>();
    	AVUser avUser = AVUser.getCurrentUser();
		if (avUser == null) {
			AntHomeApplication.storeInfos.clear();
			mHandler.post(new Runnable() {
				@Override
				public void run() {
					listener.dataRetrieved(requestId, goodsKindList);
				}
			});
			return;
		}

		final String userId = avUser.getObjectId();
        mExecutorService.submit(new Runnable()
        {
            @Override
            public void run()
            {
            	checkIsInit();

                AVQuery<GoodsKind> query = AVQuery.getQuery(GoodsKind.class);
                query.orderByAscending("showIndex");
                query.whereEndsWith(StoreInfo.ATTR_STOREID, userId);
//                query.whereEndsWith(StoreInfo.ATTR_STOREID, "558e0ebbe4b060308e3c8b78");
                query.include(GoodsKind.ATTR_STYLELIST);
                query.setCachePolicy(CachePolicy.NETWORK_ELSE_CACHE);
                try
                {
                	goodsKindList.addAll(query.find());
                } catch (AVException exception)
                {
                    Log.e(TAG, "Query AntTradeStyle failed.", exception);
                }

                if (goodsKindList != null && goodsKindList.size() > 0)
                {
                    for (int i = 0; i < goodsKindList.size(); i++)
                    {
                        GoodsKind goodsKind = goodsKindList.get(i);
                        AVRelation<AntGoodsStyles> relation = goodsKind.getRelation(GoodsKind.ATTR_STYLELIST);
                        AVQuery<AntGoodsStyles> query1 = relation.getQuery();
                        try
                        {
                        	goodsKind.setGoodsStylesList(query1.find());
                        } catch (AVException e)
                        {
                            e.printStackTrace();
                        }
                    }
                }

                mHandler.post(new Runnable()
                {
                    @Override
                    public void run()
                    {
                        listener.dataRetrieved(requestId, goodsKindList);
                    }
                });
            }
        });
    }
    
    public void getGoodsStyleByUserId(final int requestId, final RetrieveDataListener listener)
    {
    	final List<AntGoodsStyles> goodsStyleList = new ArrayList<AntGoodsStyles>();
    	AVUser avUser = AVUser.getCurrentUser();
		if (avUser == null) {
			AntHomeApplication.storeInfos.clear();
			mHandler.post(new Runnable() {
				@Override
				public void run() {
					listener.dataRetrieved(requestId, goodsStyleList);
				}
			});
			return;
		}

		final String userId = avUser.getObjectId();
        mExecutorService.submit(new Runnable()
        {
            @Override
            public void run()
            {
            	checkIsInit();

                AVQuery<AntGoodsStyles> query = AVQuery.getQuery(AntGoodsStyles.class);
                query.orderByAscending("showIndex");
                query.whereEndsWith(StoreInfo.ATTR_STOREID, userId);
//                query.whereEndsWith(StoreInfo.ATTR_STOREID, "558e0ebbe4b060308e3c8b78");
                query.setCachePolicy(CachePolicy.NETWORK_ELSE_CACHE);
                try
                {
                	goodsStyleList.addAll(query.find());
                } catch (AVException exception)
                {
                    Log.e(TAG, "Query AntTradeStyle failed.", exception);
                }

                mHandler.post(new Runnable()
                {
                    @Override
                    public void run()
                    {
                        listener.dataRetrieved(requestId, goodsStyleList);
                    }
                });
            }
        });
    }
    
    public void getGoodsKindBase(final int requestId, final RetrieveDataListener listener)
    {
        mExecutorService.submit(new Runnable()
        {
            @Override
            public void run()
            {
            	checkIsInit();
                final List<GoodsKindBase> goodsKindList = new ArrayList<GoodsKindBase>();;

                AVQuery<GoodsKindBase> query = AVQuery.getQuery(GoodsKindBase.class);
                query.orderByAscending("showIndex");
                query.include(GoodsKindBase.ATTR_STYLELIST);
                query.setCachePolicy(CachePolicy.NETWORK_ELSE_CACHE);
                try
                {
                	goodsKindList.addAll(query.find());
                } catch (AVException exception)
                {
                    Log.e(TAG, "Query AntTradeStyle failed.", exception);
                }

                if (goodsKindList != null && goodsKindList.size() > 0)
                {
                    for (int i = 0; i < goodsKindList.size(); i++)
                    {
                    	GoodsKindBase goodsKind = goodsKindList.get(i);
                        AVRelation<AntGoodsStylesBase> relation = goodsKind.getRelation(GoodsKindBase.ATTR_STYLELIST);
                        AVQuery<AntGoodsStylesBase> query1 = relation.getQuery();
                        try
                        {
                        	goodsKind.setGoodsStylesList(query1.find());
                        } catch (AVException e)
                        {
                            e.printStackTrace();
                        }
                    }
                }

                mHandler.post(new Runnable()
                {
                    @Override
                    public void run()
                    {
                        listener.dataRetrieved(requestId, goodsKindList);
                    }
                });
            }
        });
    }
    
    public void getGoodsCount(final List<String> storeIdList,
    		final int requestId,  final RetrieveDataListener listener,
    		final String kind, final String style)
    {
        mExecutorService.submit(new Runnable()
        {
            @Override
            public void run()
            {
            	checkIsInit();
                AVQuery<AntGoods> query = AVQuery.getQuery(AntGoods.class);
                query.whereContainedIn(AntGoods.ATTR_STOREID, storeIdList);
//                query.whereEqualTo(AntGoods.ATTR_IS_ON_SHELF, true);
                if(!TextUtils.isEmpty(kind)) {
                	query.whereEqualTo(AntGoods.ATTR_KIND, kind);
                }
                if(!TextUtils.isEmpty(style)) {
                	query.whereEqualTo(AntGoods.ATTR_STYLE, style);
                }
                query.setCachePolicy(CachePolicy.NETWORK_ELSE_CACHE);
                
                List<String> keyList = new ArrayList<String>();
                keyList.add(AntGoods.ATTR_OBJECTID);
                query.selectKeys(keyList);
                
                final GoodsList goodsList = new GoodsList();
                try
                {
                    goodsList.setGoodList(query.find());
                    goodsList.setTotalNum(query.count());
                    iLog.d("query.count():" + goodsList.getTotalNum() + " " + goodsList.getGoodList().size());

                    for (int i = 0; i < goodsList.getGoodList().size(); i++)
                    {
                        iLog.d("query.count(): detail:" + goodsList.getGoodList().get(i).getObjectId());
                    }
                } catch (AVException exception)
                {
                    iLog.e(TAG, "query.count() getGoodsListByCategory failed.", exception);
                }

                mHandler.post(new Runnable()
                {
                    @Override
                    public void run()
                    {
                        listener.dataRetrieved(requestId, goodsList);
                    }
                });
            }
        });
    }
    
    /**
     * 根据大类、小类、storeId列表查询
     * @param kind
     * @param style
     * @param start
     * @param expectCount
     * @param storeIdList
     * @param orderBy 按照排序0，销量；1：价格；2：更新时间
     * @param requestId
     * @param listener
     */
    public void getGoodsListByKindAndStyle(final String kind, final String style, 
    		final int start, final int expectCount, final List<String> storeIdList, final int orderBy,
    		final int requestId,  final RetrieveDataListener listener)
    {
    	Log.d("CEXX", "CEXX => getGoodsListByKindAndStyle => kind : " + kind);
    	Log.d("CEXX", "CEXX => getGoodsListByKindAndStyle => style : " + style);
    	Log.d("CEXX", "CEXX => getGoodsListByKindAndStyle => storeIdList : " + storeIdList);
    	
    	final String strOffShelf = AntHomeApplication.context.getResources().getString(R.string.goods_kind_goods_style_off_shelf);
		final String strPromotion = AntHomeApplication.context.getString(R.string.goods_kind_promotion);
		final String strAll = AntHomeApplication.context.getString(R.string.goods_kind_goods_style_all);
    	
        mExecutorService.submit(new Runnable()
        {
            @Override
            public void run()
            {
            	checkIsInit();
                AVQuery<AntGoods> query = AVQuery.getQuery(AntGoods.class);
                query.whereContainedIn(AntGoods.ATTR_STOREID, storeIdList);
                query.whereEqualTo(AntGoods.ATTR_IS_ON_SHELF, true);
                if(strOffShelf.equals(kind)) {
                	query.whereEqualTo(AntGoods.ATTR_IS_ON_SHELF, false);
                }
                else if(strPromotion.equals(kind)){
                	query.whereLessThan(AntGoods.ATTR_DISCOUNT, 10);
                	query.whereGreaterThan(AntGoods.ATTR_DISCOUNT, 0);
                }
                else {
                	query.whereEqualTo(AntGoods.ATTR_KIND, kind);
                }
                
                if(!strAll.equals(style)) {
                	query.whereEqualTo(AntGoods.ATTR_STYLE, style);
                }
                
                query.limit(expectCount);
                if (orderBy == 1)
                {
                    // 按照价格来排序
                    query.orderByAscending(AntGoods.ATTR_PRICE);
                } 
                else if (orderBy == 2)
                {
                	// 按照更新时间来排序
                    query.orderByDescending(AntGoods.ATTR_UPDATE_AT);
                } 
                else
                {
                	// 按照销量来排序
                    query.orderByDescending(AntGoods.ATTR_TOTAL_SALES);
                }
                query.setCachePolicy(CachePolicy.NETWORK_ELSE_CACHE);
                query.setSkip(start);
                
                final GoodsList goodsList = new GoodsList();
                try
                {
                    goodsList.setGoodList(query.find());
                    goodsList.setTotalNum(query.count());
                    iLog.d("query.count():" + goodsList.getTotalNum() + " " + goodsList.getGoodList().size());

                    for (int i = 0; i < goodsList.getGoodList().size(); i++)
                    {
                        iLog.d("query.count(): detail:" + goodsList.getGoodList().get(i).getObjectId());
                    }
                } catch (AVException exception)
                {
                    iLog.e(TAG, "query.count() getGoodsListByCategory failed.", exception);
                }

                mHandler.post(new Runnable()
                {
                    @Override
                    public void run()
                    {
                        listener.dataRetrieved(requestId, goodsList);
                    }
                });
            }
        });
    }
    
    public void getGoodsListFromLib(final List<String> storeIdList, final int orderBy,
    		final int requestId,  final RetrieveDataListener listener)
    {
    	Log.d("CEXX", "CEXX => getGoodsListFromLib => storeIdList : " + storeIdList);
    	
        mExecutorService.submit(new Runnable()
        {
            @Override
            public void run()
            {
            	checkIsInit();
                AVQuery<AntGoods> query = AVQuery.getQuery(AntGoods.class);
                query.whereContainedIn(AntGoods.ATTR_STOREID, storeIdList);
                query.whereEqualTo(AntGoods.ATTR_IS_FROM_LIB, true);
                if (orderBy == 1)
                {
                    // 按照价格来排序
                    query.orderByAscending(AntGoods.ATTR_PRICE);
                } 
                else if (orderBy == 2)
                {
                	// 按照更新时间来排序
                    query.orderByDescending(AntGoods.ATTR_UPDATE_AT);
                } 
                else
                {
                	// 按照销量来排序
                    query.orderByDescending(AntGoods.ATTR_TOTAL_SALES);
                }
                query.setCachePolicy(CachePolicy.NETWORK_ELSE_CACHE);
                
                final GoodsList goodsList = new GoodsList();
                try
                {
                    goodsList.setGoodList(query.find());
                    goodsList.setTotalNum(query.count());
                    iLog.d("getGoodsListFromLib query.count():" + goodsList.getTotalNum() + " " + goodsList.getGoodList().size());

                    for (int i = 0; i < goodsList.getGoodList().size(); i++)
                    {
                        iLog.d("getGoodsListFromLib query.count(): detail:" + goodsList.getGoodList().get(i).getObjectId());
                    }
                } catch (AVException exception)
                {
                    iLog.e(TAG, "getGoodsListFromLib query.count() getGoodsListFromLib failed.", exception);
                }

                mHandler.post(new Runnable()
                {
                    @Override
                    public void run()
                    {
                        listener.dataRetrieved(requestId, goodsList);
                    }
                });
            }
        });
    }
    
    public void getGoodsBySrcId(final List<String> storeIdList, final String srcId, final int requestId,  final RetrieveDataListener listener)
    {
        mExecutorService.submit(new Runnable()
        {
            @Override
            public void run()
            {
            	checkIsInit();
                AVQuery<AntGoods> query = AVQuery.getQuery(AntGoods.class);
                query.whereContainedIn(AntGoods.ATTR_STOREID, storeIdList);
                query.whereEqualTo(AntGoods.ATTR_SRCID, srcId);
                
                final GoodsList goodsList = new GoodsList();
                try
                {
                    goodsList.setGoodList(query.find());
                    goodsList.setTotalNum(query.count());
                    iLog.d("query.count():" + goodsList.getTotalNum() + " " + goodsList.getGoodList().size());

                    for (int i = 0; i < goodsList.getGoodList().size(); i++)
                    {
                        iLog.d("query.count(): detail:" + goodsList.getGoodList().get(i).getObjectId());
                    }
                } catch (AVException exception)
                {
                    iLog.e(TAG, "query.count() getGoodsListByCategory failed.", exception);
                }

                mHandler.post(new Runnable()
                {
                    @Override
                    public void run()
                    {
                        listener.dataRetrieved(requestId, goodsList);
                    }
                });
            }
        });
    }
    
    /**
     * 根据大类、小类、storeId列表查询
     * @param kind
     * @param style
     * @param start
     * @param expectCount
     * @param storeIdList
     * @param orderBy 按照排序0，销量；1：价格；2：更新时间
     * @param requestId
     * @param listener
     */
    public void getGoodsBaseListByKindAndStyle(final String kind, final String style, 
    		final int start, final int expectCount, final int orderBy,
    		final int requestId,  final RetrieveDataListener listener)
    {
    	Log.d("CEXX", "CEXX => getGoodsBaseListByKindAndStyle => kind : " + kind);
    	Log.d("CEXX", "CEXX => getGoodsBaseListByKindAndStyle => style : " + style);
    	
		final String strAll = AntHomeApplication.context.getString(R.string.goods_kind_goods_style_all);
    	
        mExecutorService.submit(new Runnable()
        {
            @Override
            public void run()
            {
            	checkIsInit();
                AVQuery<AntGoodsBase> query = AVQuery.getQuery(AntGoodsBase.class);
                
                if(!strAll.equals(kind)){
                	query.whereEqualTo(AntGoods.ATTR_KIND, kind);
                }
                
                if(!strAll.equals(style)) {
                	query.whereEqualTo(AntGoods.ATTR_STYLE, style);
                }
                
                query.limit(expectCount);
                if (orderBy == 1)
                {
                    // 按照价格来排序
                    query.orderByAscending(AntGoods.ATTR_PRICE);
                } 
                else if (orderBy == 2)
                {
                	// 按照更新时间来排序
                    query.orderByDescending(AntGoods.ATTR_UPDATE_AT);
                } 
                query.setCachePolicy(CachePolicy.NETWORK_ELSE_CACHE);
                query.setSkip(start);
                
                final GoodsBaseList goodsList = new GoodsBaseList();
                try
                {
                    goodsList.setGoodList(query.find());
                    goodsList.setTotalNum(query.count());
                    iLog.d("query.count():" + goodsList.getTotalNum() + " " + goodsList.getGoodList().size());

                    for (int i = 0; i < goodsList.getGoodList().size(); i++)
                    {
                        iLog.d("query.count(): detail:" + goodsList.getGoodList().get(i).getObjectId());
                    }
                } catch (AVException exception)
                {
                    iLog.e(TAG, "query.count() getGoodsListByCategory failed.", exception);
                }

                mHandler.post(new Runnable()
                {
                    @Override
                    public void run()
                    {
                        listener.dataRetrieved(requestId, goodsList);
                    }
                });
            }
        });
    }
    
    /**
     * 获取我的收入信息
     * @param requestId
     * @param listener
     * @return 返回对象为空的时候，保存不成功；不为空则成功
     */
    public void getIncomeInfo(final String userId, final int requestId,
        final RetrieveDataListener listener)
    {
        mExecutorService.submit(new Runnable()
        {
            @Override
            public void run()
            {
                checkIsInit();
                AVQuery<IncomeInfo> query = AVQuery
                    .getQuery(IncomeInfo.class);

                query.whereEqualTo(IncomeInfo.ATTR_userId, userId);
                try
                {
                    final IncomeInfo antGoodsBase = query.getFirst();
                    mHandler.post(new Runnable()
                    {
                        @Override
                        public void run()
                        {
                            if (listener != null)
                            {
                                listener.dataRetrieved(requestId, antGoodsBase);
                            }

                        }
                    });
                } catch (AVException e)
                {
                    e.printStackTrace();
                    mHandler.post(new Runnable()
                    {
                        @Override
                        public void run()
                        {
                            if (listener != null)
                            {
                                listener.dataRetrieved(requestId, null);
                            }

                        }
                    });
                }

            }
        });
    }
    
    public void checkAndSaveStyle(final AntGoodsStyles goodsStyle, final int requestId, final RetrieveDataListener listener)
    {
		final String userId = goodsStyle.getUserId();
        mExecutorService.submit(new Runnable()
        {
            @Override
            public void run()
            {
            	boolean have = false;
            	AntGoodsStyles tempStyle = null;
            	
            	checkIsInit();
                AVQuery<AntGoodsStyles> query = AVQuery.getQuery(AntGoodsStyles.class);
                query.whereEqualTo(StoreInfo.ATTR_STOREID, userId);
                query.setCachePolicy(CachePolicy.NETWORK_ELSE_CACHE);
                try
                {
                	List<AntGoodsStyles> styleList = query.find();
                	Log.d("CEXX", "CEXX => checkAndSaveStyle => styleList : " + styleList);
                	if(styleList != null && styleList.size() > 0) {
                		String goodsStyleName = goodsStyle.getName();
                		Log.d("CEXX", "CEXX => checkAndSaveStyle => goodsStyleName : " + goodsStyleName);
                		goodsStyleName = (goodsStyleName==null ? "" : goodsStyleName);
                		for(AntGoodsStyles style : styleList) {
                			String styleName = style.getName();
                			styleName = (styleName==null ? "" : styleName);
                			if(styleName.equals(goodsStyleName)) {
                				have = true;
                				tempStyle = style;
                				break;
                			}
                		}
                	}
                	
                } 
                catch (Exception exception)
                {
                    Log.e(TAG, "Query AntTradeStyle failed.", exception);
                }

                Log.d("CEXX", "CEXX => checkAndSaveStyle => have : " + have);
                if(!have) {
                	goodsStyle.saveInBackground(new SaveCallback() {
						@Override
						public void done(AVException arg0) {
							listener.dataRetrieved(requestId, goodsStyle);
						}
					});
                }
                else {
                	listener.dataRetrieved(requestId, tempStyle);
                }
            }
        });
    }
    
    public void checkAndSaveKind(final GoodsKind goodsKind, final AntGoodsStyles style, 
    		final int requestId, final RetrieveDataListener listener)
    {
		final String userId = goodsKind.getUserId();
        mExecutorService.submit(new Runnable()
        {
            @Override
            public void run()
            {
            	boolean have = false;
            	GoodsKind tempKind = null;
            	
            	checkIsInit();
                AVQuery<GoodsKind> query = AVQuery.getQuery(GoodsKind.class);
                query.whereEqualTo(StoreInfo.ATTR_STOREID, userId);
                query.setCachePolicy(CachePolicy.NETWORK_ELSE_CACHE);
                try
                {
                	List<GoodsKind> kindList = query.find();
                	if(kindList != null && kindList.size() > 0) {
                		String goodsKindName = goodsKind.getName();
                		goodsKindName = (goodsKindName==null ? "" : goodsKindName);
                		for(GoodsKind kind : kindList) {
                			String kindName = kind.getName();
                			kindName = (kindName==null ? "" : kindName);
                			if(kindName.equals(goodsKindName)) {
                				have = true;
                				tempKind = kind;
                				break;
                			}
                		}
                	}
                	
                } 
                catch (Exception exception)
                {
                    Log.e(TAG, "Query AntTradeStyle failed.", exception);
                }

                Log.d("CEXX", "CEXX => checkAndSaveKind => have : " + have);
                if(!have) {
                	goodsKind.saveInBackground(new SaveCallback() {
						@Override
						public void done(AVException arg0) {
							listener.dataRetrieved(requestId, goodsKind);
						}
					});
                }
                else {
                	try {
                		boolean have1 = false;
                		List<AntGoodsStyles> styleList = tempKind.getStyleRelation().getQuery().find();
                		for(AntGoodsStyles tempStyle : styleList) {
                			if(style.getName().equals(tempStyle.getName())) {
                				have1 = true;
                				break;
                			}
                		}
                		
                		Log.d("CEXX", "CEXX => checkAndSaveKind => have1 : " + have1);
                		if(!have1) {
                			tempKind.getStyleRelation().add(style);
                			tempKind.save();
                		}
					} catch (Exception e) {
						e.printStackTrace();
					}
                	listener.dataRetrieved(requestId, tempKind);
                }
            }
        });
    }
    
    public void deleteGoods(final AntGoods antGoods, final GoodsKind goodsKind, final AntGoodsStyles goodsStyles,
    		final RetrieveDataListener listener) {
    	if(antGoods == null) {
    		return;
    	}
    	
    	final boolean isFromLib = antGoods.isFromLib();
    	final AVFile imageFile = antGoods.getImageFile();
    	final String style = antGoods.getStyle();
    	final String kind = antGoods.getKind();
    	antGoods.deleteInBackground(new DeleteCallback() {
			@Override
			public void done(AVException arg0) {
				if(listener != null) {
					listener.dataRetrieved(-1, arg0);
				}
				
				if(arg0 == null) {
					// 删除商品的图片
					Log.d("CEXX", "CEXX => delete image file => isFromLib : " + isFromLib);
					Log.d("CEXX", "CEXX => delete image file => imageFile : " + imageFile);
					if(!isFromLib && imageFile != null) {
						imageFile.deleteInBackground();
					}
					// 查询商品数，条件满足时删除style和kind
					List<String> storeIdList = new ArrayList<String>();
					storeIdList.add(AntHomeApplication.sCurrentStoreInfo.getStoreid());
					getGoodsCount(storeIdList, -1, new RetrieveDataListener() {
						@Override
						public void dataRetrieved(int requestId, Object data) {
							Log.d("CEXX", "CEXX => goods cound => data : " + data);
							if (data != null) {
								GoodsList goodsList = (GoodsList) data;
								Log.d("CEXX", "CEXX => goods cound => totalNum : " + goodsList.getTotalNum());
								if(goodsList.getTotalNum() == 0) {
									goodsStyles.deleteInBackground(new DeleteCallback() {
										@Override
										public void done(AVException arg0) {
											Log.d("CEXX", "CEXX => goods cound 00 => arg0 : " + arg0);
											if(arg0 == null) {
												if(listener != null) {
													listener.dataRetrieved(-1, goodsStyles);
												}
											}
										}
									});
									
									List<AntGoodsStyles> styleList = goodsKind.getGoodsStylesList();
									styleList.remove(goodsStyles);
									int styleCount = 0;
									for(AntGoodsStyles antGoodsStyle : styleList) {
										if(!TextUtils.isEmpty(antGoodsStyle.getName())) {
											Log.d("CEXX", "CEXX => goods cound 01 => styleName : " + antGoodsStyle.getName());
											styleCount++;
										}
									}
									Log.d("CEXX", "CEXX => goods cound 01 => styleCount : " + styleCount);
									if(styleCount == 1) {
										goodsKind.deleteInBackground(new DeleteCallback() {
											@Override
											public void done(AVException arg0) {
												Log.d("CEXX", "CEXX => goods cound 01 => arg0 : " + arg0);
												if(arg0 == null) {
													if(listener != null) {
														listener.dataRetrieved(-1, goodsKind);
													}
												}
											}
										});
									}
								}
							}
						}
					}, kind, style);
				}
			}
		});
    }
    
    /**
     * 获取我的订单
     * @param userId
     * @param orderTypes
     * @param requestId
     * @param listener
     * @since 3.8
     */
    public void getMyWebDeposit(final String userId, final int orderType,
        final int start, final int expectedCount, final int requestId,
        final RetrieveDataListener listener)
    {
        mExecutorService.submit(new Runnable()
        {
            @Override
            public void run()
            {
                checkIsInit();
                try
                {
                    final AVQuery<Order> query = AVQuery.getQuery(Order.class);
                   // query.whereEqualTo(Order.ATTR_CUSTOMID, userId);
                    iLog.d(TAG, "ATTR_CUSTOMID:"+userId);
                    // TODO 替换为商店的ID
                    query.whereEqualTo(Order.ATTR_STOREID, userId);
                  
					if (EarningListFragment.EARNING_TYPE_SALES == orderType) {
						 //销售
						 query.whereEqualTo(Order.ATTR_ISACCOUNTED, true);
					} else if (EarningListFragment.EARNING_TYPE_COMMISSION == orderType) {
						//代售的判断条件：当订单类型为orderType==sp且
						//storeId对应的storeInfo里的usePickupStation为true时，
						//且pickupstationid==当前店铺的id
						query.whereEqualTo(Order.ATTR_ORDERTYPE, 0);//sp
						query.whereEqualTo(Order.ATTR_PICKUPSTATIONID, userId);
						if(AntHomeApplication.storeInfos.get(userId).isUsePickUpStation())
						{
							
						}
						else{
							mHandler.post(new Runnable()
		                    {
		                        @Override
		                        public void run()
		                        {
		                            listener.dataRetrieved(requestId, null);
		                        }
		                    });
							//条件不满足直接返回,
							return;
						}
					}
                    query.setSkip(start);
                    query.limit(expectedCount);
                    query.setCachePolicy(CachePolicy.NETWORK_ELSE_CACHE);

                    query.orderByDescending(Order.ATTR_CREATED_AT);

                    final OrderList orderList = new OrderList();
                    orderList.setOrderList(query.find());
                    orderList.setTotalNum(query.count());

                    mHandler.post(new Runnable()
                    {
                        @Override
                        public void run()
                        {
                            listener.dataRetrieved(requestId, orderList);
                        }
                    });
                    
                } catch (Exception e)
                {
                    iLog.e(TAG, "getMyOrderByType", e);
                    e.printStackTrace();
                    mHandler.post(new Runnable()
                    {
                        @Override
                        public void run()
                        {
                            listener.dataRetrieved(requestId, null);
                        }
                    });
                }

            }
        });
    }
   
    /**
     * 获取我的代收
     * @param userId
     * @param orderTypes
     * @param requestId
     * @param listener
     * @since 3.8
     */
    public void getEMRecv(final String userId, final int orderType,
        final int start, final int expectedCount, final int requestId,
        final RetrieveDataListener listener)
    {
        mExecutorService.submit(new Runnable()
        {
            @Override
            public void run()
            {
                checkIsInit();
                try
                {
                    final AVQuery<EMRecv> query = AVQuery.getQuery(EMRecv.class);
                   // query.whereEqualTo(Order.ATTR_CUSTOMID, userId);
                    iLog.d(TAG, "ATTR_CUSTOMID:"+userId);
                    
                    AVQuery<StoreInfo> innerQuery = AVQuery.getQuery(StoreInfo.class);
                    innerQuery.whereEqualTo(StoreInfo.ATTR_STOREID, userId);
                    query.whereMatchesQuery(EMRecv.STORE, innerQuery);
                    
                    query.include(EMRecv.EMCOMPANY);
                    query.setSkip(start);
                    query.limit(expectedCount);
                    query.setCachePolicy(CachePolicy.NETWORK_ELSE_CACHE);

                    query.orderByDescending(Order.ATTR_CREATED_AT);

                    final EMRecvList orderList = new EMRecvList();
                   List<EMRecv> list = query.find();
                   if(list!=null&&list.size()>0)
                   {
                       for(int i=0;i<list.size();i++)
                       {
                           EMRecv emrecv= list.get(i);
                           AVRelation<EMCompany> relation =emrecv.getRelation(EMRecv.EMCOMPANY);
                           AVQuery<EMCompany> query1 = relation.getQuery();
                           try {
                               List<EMCompany> list1 = query1.find();
                               if(list1!=null&&list1.size()>0)
                               {
                                   emrecv.setEMCompany(list1.get(0));
                               }
                              
                           } catch (AVException e) {
                               e.printStackTrace();
                           }
                       }
                   }
                    orderList.setEmrecvList(list);
                    
                    orderList.setTotalNum(query.count());

                    mHandler.post(new Runnable()
                    {
                        @Override
                        public void run()
                        {
                            listener.dataRetrieved(requestId, orderList);
                        }
                    });
                    
                } catch (Exception e)
                {
                    iLog.e(TAG, "getMyOrderByType", e);
                    e.printStackTrace();
                    mHandler.post(new Runnable()
                    {
                        @Override
                        public void run()
                        {
                            listener.dataRetrieved(requestId, null);
                        }
                    });
                }

            }
        });
    }
    
    
    /**
     * 获取我的代收
     * @param userId
     * @param orderTypes
     * @param requestId
     * @param listener
     * @since 3.8
     */
    public void getEMRecvExportInport(final String userId, final int emrecvType,
        final int start, final int expectedCount, final int requestId,
        final RetrieveDataListener listener)
    {
        mExecutorService.submit(new Runnable()
        {
            @Override
            public void run()
            {
                checkIsInit();
                try
                {
                    final AVQuery<EMRecv> query = AVQuery.getQuery(EMRecv.class);
                   // query.whereEqualTo(Order.ATTR_CUSTOMID, userId);
                    iLog.d(TAG, "ATTR_CUSTOMID:"+userId);
                    
                    AVQuery<StoreInfo> innerQuery = AVQuery.getQuery(StoreInfo.class);
                    innerQuery.whereEqualTo(StoreInfo.ATTR_STOREID, userId);
                    query.whereMatchesQuery(EMRecv.STORE, innerQuery);
                    
                    query.include(EMRecv.EMCOMPANY);
                    query.setSkip(start);
                    query.limit(expectedCount);
                    query.whereEqualTo(EMRecv.STATUS, emrecvType);
                    
                    query.setCachePolicy(CachePolicy.NETWORK_ELSE_CACHE);

                    query.orderByDescending(Order.ATTR_CREATED_AT);

                    final EMRecvList orderList = new EMRecvList();
                   List<EMRecv> list = query.find();
                   if(list!=null&&list.size()>0)
                   {
                       for(int i=0;i<list.size();i++)
                       {
                           EMRecv emrecv= list.get(i);
                           AVRelation<EMCompany> relation =emrecv.getRelation(EMRecv.EMCOMPANY);
                           AVQuery<EMCompany> query1 = relation.getQuery();
                           try {
                               List<EMCompany> list1 = query1.find();
                               if(list1!=null&&list1.size()>0)
                               {
                                   emrecv.setEMCompany(list1.get(0));
                               }
                              
                           } catch (AVException e) {
                               e.printStackTrace();
                           }
                       }
                   }
                    orderList.setEmrecvList(list);
                    
                    orderList.setTotalNum(query.count());

                    mHandler.post(new Runnable()
                    {
                        @Override
                        public void run()
                        {
                            listener.dataRetrieved(requestId, orderList);
                        }
                    });
                    
                } catch (Exception e)
                {
                    iLog.e(TAG, "getMyOrderByType", e);
                    e.printStackTrace();
                    mHandler.post(new Runnable()
                    {
                        @Override
                        public void run()
                        {
                            listener.dataRetrieved(requestId, null);
                        }
                    });
                }

            }
        });
    }
    
	public void getEmrecvCompany(final int requestId, final RetrieveDataListener listener) {

		mExecutorService.submit(new Runnable() {
			@Override
			public void run() {
				checkIsInit();
				AVQuery<EMCompany> query = AVQuery.getQuery(EMCompany.class);
				query.setCachePolicy(CachePolicy.NETWORK_ELSE_CACHE);
				
				final List<EMCompany> storeInfoList=new ArrayList<EMCompany>();
				try {
					List<EMCompany> temp = query.find();
					if (temp != null && temp.size() > 0) {
						storeInfoList.addAll(temp);
					}
				} catch (AVException e) {
					e.printStackTrace();
				}

				mHandler.post(new Runnable() {
					@Override
					public void run() {
						AntHomeApplication.storeInfos.clear();
						for(EMCompany si : storeInfoList) {
							AntHomeApplication.emcompanyInfos.put(si.getCompanyName(), si);
						}
						
						if (listener != null) {
							listener.dataRetrieved(requestId, storeInfoList);
						}
					}
				});
			}
		});
	}
	
	public void makeEmrecv(final List<EMRecv> orderItemList, final int requestId, final RetrieveDataListener listener) {

		mExecutorService.submit(new Runnable() {
			@Override
			public void run() {
				checkIsInit();

				if (orderItemList != null && orderItemList.size() > 1) {

					String storeId = "";

					AVUser user11 = AVUser.getCurrentUser();
					if (user11 != null) {
						storeId = user11.getObjectId();
					}
					StoreInfo storeInfo = AntHomeApplication.storeInfos.get(storeId);
					iLog.d("makeEmrecv storeId:"+storeId+" storeInfo:"+storeInfo);
					if (storeInfo != null)
						iLog.d("makeEmrecv storeId:" + storeId + " " + storeInfo.getDescrip());
					else{
						AVQuery<StoreInfo> query = AVQuery.getQuery(StoreInfo.class);
						query.setCachePolicy(CachePolicy.NETWORK_ELSE_CACHE);
						query.whereEqualTo(StoreInfo.ATTR_STOREID, storeId);
						try {
							storeInfo=query.getFirst();
							AntHomeApplication.storeInfos.put(storeId, storeInfo);
						} catch (AVException e) {
							e.printStackTrace();
						}
					}

					List<String> phones = new ArrayList<String>();
					List<String> emIds = new ArrayList<String>();
					for (int i = 0; i < orderItemList.size() - 1; i++) {
						EMCompany em = orderItemList.get(i).getEMCompany();
						orderItemList.get(i).getRelation(EMRecv.EMCOMPANY).add(em);
						if (storeInfo != null) {
							orderItemList.get(i).getRelation(EMRecv.STORE).add(storeInfo);
						}
						phones.add(orderItemList.get(i).getReceiverPhone());
						if(!TextUtils.isEmpty(orderItemList.get(i).getEMId()))
						emIds.add(orderItemList.get(i).getEMId());
						
					}

					AVQuery<AVUser> user = AVUser.getUserQuery(AVUser.class);// AVUser.getQuery();

					user.whereContainedIn("mobilePhoneNumber", phones);
					try {
						List<AVUser> list = user.find();
						if (list != null && list.size() > 0) {
							// iLog.d("makeEmrecv AVUser list1:"+list.size());
							for (int i = 0; i < orderItemList.size() - 1; i++) {
								EMRecv em = orderItemList.get(i);
								// iLog.d("makeEmrecv AVUser
								// list2:"+em.getReceiverPhone());
								for (int j = 0; j < list.size(); j++) {
									// iLog.d("makeEmrecv AVUser
									// list3:"+list.get(j).getString("mobilePhoneNumber")+"
									// "+list.get(j).toJSONObject().toString());
									if (!TextUtils.isEmpty(em.getReceiverPhone()) && em.getReceiverPhone()
											.equals(list.get(j).getString("mobilePhoneNumber"))) {
										// iLog.d("makeEmrecv AVUser
										// list4:"+em.getReceiverPhone());
										em.setReceiverAddr(list.get(j).getString("realAddress"));
										em.setReceiverName(list.get(j).getString("realname"));
										em.setUserId(list.get(j).getObjectId());
									}

								}
							}
						}
					} catch (AVException e) {
						e.printStackTrace();
					}
					//删除最后一个无用数据
					orderItemList.remove(orderItemList.size()-1);
					
					
					AVQuery<EMRecv> em = AVQuery.getQuery(EMRecv.class);// AVUser.getQuery();
					em.whereContainedIn(EMRecv.EMID, emIds);
					try {
						List<EMRecv> tempList = em.find();
						if (tempList != null && tempList.size() > 0) {
							for (int j = 0; j < tempList.size(); j++) {
								EMRecv emSss = tempList.get(j);
								for (int i = 0; i < orderItemList.size(); i++) {
									EMRecv emSs = orderItemList.get(i);
									if (emSss.getEMId().equals(emSs.getEMId())) {
										orderItemList.remove(i);
										i--;
									}
								}

							}
						}
					} catch (AVException e) {
						e.printStackTrace();
					}
					
					AVObject.saveAllInBackground(orderItemList, new SaveCallback() {

						@Override
						public void done(final AVException arg0) {
							mHandler.post(new Runnable() {
								@Override
								public void run() {

									if (listener != null) {
										if (arg0 == null) {
											listener.dataRetrieved(requestId, new Object());
										} else {
											listener.dataRetrieved(requestId, null);
										}

									}
								}
							});
						}
					});
				} else {

					mHandler.post(new Runnable() {
						@Override
						public void run() {

							if (listener != null) {
								listener.dataRetrieved(requestId, null);

							}
						}
					});
				}

			}
		});
	}
	
	
/**
 * 快递出库
 * @param emCode
 * @param status
 * @param requestId
 * @param listener
 */
	public void updateEmrecvStatus(final String emCode, final int status, final int requestId,
			final RetrieveDataListener listener) {
		mExecutorService.submit(new Runnable() {
			@Override
			public void run() {
				checkIsInit();
				try {

					String userId = "";

					AVUser user = AVUser.getCurrentUser();
					if (user != null) {
						userId = user.getObjectId();
					}
					// 只能修改自己店鋪收到的快件
					AVQuery<EMRecv> em = AVQuery.getQuery(EMRecv.class);

					if (!TextUtils.isEmpty(userId)) {
						AVQuery<StoreInfo> innerQuery = AVQuery.getQuery(StoreInfo.class);
						innerQuery.whereEqualTo(StoreInfo.ATTR_STOREID, userId);
						em.whereMatchesQuery(EMRecv.STORE, innerQuery);
					}
					em.whereNotEqualTo(EMRecv.STATUS, status);
					em.whereEqualTo(EMRecv.EMCODE, emCode);
					final EMRecv emRecv = em.getFirst();
					emRecv.setStatus(status);
					Date date=new Date();
					date.setTime(System.currentTimeMillis());
					emRecv.setSingedTime(date);
					emRecv.save();
					mHandler.post(new Runnable() {
						@Override
						public void run() {
							listener.dataRetrieved(requestId, emRecv);
						}
					});
				} catch (Exception e) {
					e.printStackTrace();
					mHandler.post(new Runnable() {
						@Override
						public void run() {
							listener.dataRetrieved(requestId, null);
						}
					});
				}

			}
		});
	}
	
	public void getWithdrawRecordList(final int requestId, final RetrieveDataListener listener) {
		mExecutorService.submit(new Runnable() {
			@Override
			public void run() {
				final List<WithdrawRecord> withdrawRecordList = new ArrayList<WithdrawRecord>();
				AVUser avUser = AVUser.getCurrentUser();
				if(avUser != null) {
					checkIsInit();
					AVQuery<WithdrawRecord> query = AVQuery.getQuery(WithdrawRecord.class);
					query.whereEqualTo(WithdrawRecord.ATTR_userId, avUser.getObjectId());
					query.setCachePolicy(CachePolicy.NETWORK_ELSE_CACHE);
					try {
						List<WithdrawRecord> tempList = query.find();
						if (tempList != null && tempList.size() > 0) {
							withdrawRecordList.addAll(tempList);
						}
					} catch (AVException e) {
						e.printStackTrace();
					}
				}

				mHandler.post(new Runnable() {
					@Override
					public void run() {
						if (listener != null) {
							listener.dataRetrieved(requestId, withdrawRecordList);
						}
					}
				});
			}
		});
	}
	
	public void getUserIdentification(final int requestId, final RetrieveDataListener listener) {
		mExecutorService.submit(new Runnable() {
			@Override
			public void run() {
				UserIdentification tempUserIdentification = null;
				Object tempErrorObj = null;
				AVUser avUser = AVUser.getCurrentUser();
				if(avUser != null) {
					checkIsInit();
					AVQuery<UserIdentification> query = AVQuery.getQuery(UserIdentification.class);
					query.whereEqualTo(UserIdentification.ATTR_userId, avUser.getObjectId());
					try {
						tempUserIdentification = query.getFirst();
					} catch (AVException e) {
						tempErrorObj = new Object();
						e.printStackTrace();
					}
				}

				final UserIdentification userIdentification = tempUserIdentification;
				final Object errorObj = tempErrorObj;
				mHandler.post(new Runnable() {
					@Override
					public void run() {
						if (listener != null) {
							if(errorObj != null) {
								listener.dataRetrieved(requestId, errorObj);
							} else {
								listener.dataRetrieved(requestId, userIdentification);
							}
						}
					}
				});
			}
		});
	}
}
